package com.bsj.media.init;

import com.alibaba.fastjson.JSON;
import com.bsj.media.init.check.NowChannelCheckThread;
import com.bsj.springQueue.gatewayHandle.TimeoutRun;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * 检测链路自动关闭
 */
@Slf4j
public class NettyConnectUntil {

//    private static ChannelCheckThread channelCheckThread;
    private static NowChannelCheckThread channelCheckThread;

    public static void start() {
        channelCheckThread = new NowChannelCheckThread(10 * 1000);
        channelCheckThread.start(new TimeoutRun() {
            @Override
            public void delChannel(ChannelHandlerContext channelHandlerContext) {
                if (channelHandlerContext == null) {
                    return;
                }
                //获得sim和通道key值
                String simChannel = CachedChannelMap.delKey(channelHandlerContext);
                if (!StringUtils.isEmpty(simChannel)) {
                    //删除播放链路对应的链接链路
                    log.warn("删除通道simChannel: {}", simChannel);
                    SendChannelUntil.del(simChannel, channelHandlerContext);
                } else {
                    SocketAddress socketAddress = channelHandlerContext.channel().remoteAddress();
                    if (socketAddress instanceof InetSocketAddress) {
                        InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                        String ip = inetSocketAddress.getAddress().getHostAddress();
                        log.warn("删除通道时，不知道链路管道:" + ip);
                    } else {
                        log.warn("删除通道时，不知道链路管道:" + JSON.toJSONString(socketAddress));
                    }
                }
            }
        });
    }

    public static void push(ChannelHandlerContext channelHandlerContext) {
        channelCheckThread.push(channelHandlerContext);
    }

    public static void del(ChannelHandlerContext channelHandlerContext) {
        channelCheckThread.delChannelHandlerContext(channelHandlerContext);
    }

    public static void add(ChannelHandlerContext channelHandlerContext) {
        channelCheckThread.add(channelHandlerContext);
    }

    public static void stop() {
        channelCheckThread.stop();
    }
}
